package io.coderyeah.ymcc.mq;

import io.coderyeah.ymcc.domain.CourseOrder;
import io.coderyeah.ymcc.domain.MediaFile;
import io.coderyeah.ymcc.dto.PayMsgInMQ;
import io.coderyeah.ymcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * @author lqs
 * @date 2022/11/4 13:03
 */
//保存课程订单以及支付订单的事务消息
@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-order-producer")
public class CourseOrderListener implements RocketMQLocalTransactionListener {// 事务消息监听

    @Autowired
    private ICourseOrderService courseOrderService;

    // 事务监听
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        // arg 是额外参数 用于执行订单的添加
        if (arg instanceof CourseOrder) {
            try {
                // 类型强转
                CourseOrder order = (CourseOrder) arg;
                // 保存课程订单和明细
                courseOrderService.saveCourseOrderAndItem(order);
                return RocketMQLocalTransactionState.COMMIT;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    // 事务检查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 当mq服务长时间没有接收到指令时会调用此方法检查事务是否正常执行
        if (msg.getPayload() instanceof PayMsgInMQ) {
            try {
                PayMsgInMQ msgInMQ = (PayMsgInMQ) msg.getPayload();
                // 通过订单号查询订单是否已经保存
                CourseOrder order = courseOrderService.getByOrderNo(msgInMQ.getOrderNo());
                if (order != null) {
                    return RocketMQLocalTransactionState.COMMIT;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
